package com.kgcx.order.common;

import com.kgcx.common.bean.ReturnData;
//import com.kgcx.price.rabbitmq.BaseInfoProducer;
import com.kgcx.common.constant.ResultCode;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class MqttListenerUtil
{
    public static final Logger logger = LoggerFactory.getLogger(MqttListenerUtil.class);

    @Autowired
    private MqttClient mqttClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Autowired
//    private BaseInfoProducer baseInfoProducer;

    //重新链接
    /*public void startReconnect() {
        if (!client.isConnected()) {
            try {
                client.connect(options);
            } catch (MqttSecurityException e) {
                e.printStackTrace();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }*/

  /*  public void disconnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }*/

    public ReturnData subscribeMqttMessage(int[] qos, String[] topics)
    {
        try
        {
            mqttClient.setCallback(new MqttListenerCallback(mqttClient));
            mqttClient.subscribe(topics, qos);
        }
        catch (MqttException e)
        {
            logger.error("mqtt客户端订阅消息失败：" + e.getMessage());

            if(e.getReasonCode() == MqttException.REASON_CODE_CLIENT_ALREADY_DISCONNECTED)
            {
                if(!mqttClient.isConnected())
                {
                    try
                    {
                        mqttClient.reconnect();
                    }
                    catch (MqttException e1)
                    {
                        e1.printStackTrace();
                        logger.error("mqtt客户端重连失败：" + e.getMessage());
                    }
                }
            }
            new ReturnData(ResultCode.FAIL, "mqtt客户端订阅消息失败：" + e.getMessage());
        }

        return new ReturnData(ResultCode.SUCCESS, "mqtt客户端订阅消息成功");
    }

}
